﻿using CarAppClient.Consts;
using CarAppClient.Controls.MessageUsercontrols;
using CarAppClient.Extension;
using CarAppClient.Helpers;
using CarAppClient.ViewModels;
using System.Collections.ObjectModel;
using CarAppClient.Views.Country;
using DelegateCommand = D.WPF.MVVM.EventUtil.DelegateCommand;
using CarAppClient.Views.CarParts.ViewModels.CarParts;
using CarAppDto.CarParts.CarPartsDtos;
using SqlSugar;
using CarAppClient.Views.CarParts;
using System.Linq;
using CarAppClient.Views.CarType;
using CarAppClient.Views.CarType.ViewModels.CarType;
using CarAppDto.CarType.AreaDtos;
using CarAppDto.CarType.CountryDtos;
using CarAppDto.CarType.BrandDtos;
using CarAppDto.CarType.VehicleSeriesDtos;
using CarAppClient.Views.CarType.Views.VehicleSeries;
using CarAppClient.Views.CarType.Views.Brand;
using D.UtilCore.Dtos;
using CarAppDto.CarType.CarTypeVersionDtos;
using CarAppClient.Views.CarType.Views.CarTypeVersion;
using CarAppDto.CarType.CarTypeDtos;
using CarAppClient.Views.CarType.Views.CarType;
using System.Xml.Linq;
using CarAppDto.Common;

namespace CarAppClient.Views.CarTypeVersion.ViewModels.CarTypeVersion
{
    public class CarTypeVersionModifyViewModel : BaseModifyViewModel<Page_CarTypeVersion_Modify>
    {      
        #region 加载页面数据

        public CarTypeVersionModifyViewModel(Page_CarTypeVersion_Modify owner, string? id, ViewStatus? viewStatus) : base(owner, id, viewStatus)
        {
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="repCarTypeVersion"></param>
        protected async override void LoadData()
        {
            if (!string.IsNullOrEmpty(Id))
            {
                // 请求后端接口 
                var res = await HttpHelper<RepCarTypeVersion>.GetAsync($"{ApiUrl.GetCarTypeVersion}/{Id}");

                //  判断结果
                if (res.Code == StatusCodeEnum.Waring)
                {
                    MsgUtil.Error(res.ErrorMsg);
                }
                else if (res.Code == StatusCodeEnum.Error)
                {
                    MsgUtil.Error("服务器异常");
                }
                else
                {
                    // 绑定数据源到UI 
                    if (res.Data != null)
                    {                     
                        Code = res.Data.Code;
                        Code = res.Data.Code;
                        Version = res.Data.Version;
                        SalesName = res.Data.SalesName;

                        var resBrand = await HttpHelper<RepBrand>.GetAsync($"{ApiUrl.GetBrand}/{res.Data.BrandId}");
                        repBrand = resBrand.Data;
                        Brand = repBrand?.Name;

                        var resVehicleSeries = await HttpHelper<RepVehicleSeries>.GetAsync($"{ApiUrl.GetVehicleSeries}/{res.Data.VehicleSeriesId}");
                        repVehicleSeries = resVehicleSeries.Data;
                        VehicleSeries = repVehicleSeries?.Name;

                        var resCarType = await HttpHelper<RepCarType>.GetAsync($"{ApiUrl.GetCarType}/{res.Data.CarTypeId}");
                        repCarType = resCarType.Data;
                        CarType = repCarType?.Name;
                        List<string> delectCarPartsList= res.Data.CarPartsCarTypeVersionList.Where(a=>a.State==2).Select(a=>a.Id).ToList();

                        // 生成配件列表数据
                        //var resRepCarType = await HttpHelper<RepCarType>.GetAsync($"{ApiUrl.GetCarType}/{repCarType?.Id}");
                        var resRepCarType = await HttpHelper<List<RepCarParts>>.GetAsync($"{ApiUrl.GetCarPartsByCarTypeId}/{res.Data.CarTypeId}");
                        if (resRepCarType != null && resRepCarType.Data != null)
                        {

                            resRepCarType.Data.ForEach(carPart => {
                                RepCarPartsList.Add(new RepCarPartsCarTypeVersion()
                                {
                                    CarPartsTypeName = carPart.VehicleSeriesCarPartsTypeEntityName,
                                    Name = carPart.Name,
                                    Code = carPart.Code,
                                    Id= carPart.Id,
                                    State = delectCarPartsList.Contains(carPart.Id)?2:- 1,
                                    Type = 1,
                                    IsSelected=false
                                });
                            });
                        }

                        List<RepCarPartsCarTypeVersion> addCarPartsList = res.Data.CarPartsCarTypeVersionList.Where(a => a.State == 0).ToList();
                        addCarPartsList.ForEach(carPart =>
                        {
                            RepCarPartsList.Add(new RepCarPartsCarTypeVersion()
                            {
                                CarPartsTypeName = carPart.CarPartsTypeName,
                                Name = carPart.Name,
                                Id = carPart.Id,
                                Code = carPart.Code,
                                State = 0,
                                Type = 2
                            });
                        });
                    }
                }
            }
        }
        #endregion

        #region 新增、修改 参数

        private string? salesName;
        /// <summary>
        /// 销售名称
        /// </summary>
        public string? SalesName
        {
            get { return salesName; }
            set { salesName = value; RaisePropertyChanged(); }
        }

        private string? code;
        /// <summary>
        /// 编号
        /// </summary>
        public string? Code
        {
            get { return code; }
            set { code = value; RaisePropertyChanged(); }
        }

        private string? version;
        /// <summary>
        /// 车型版本
        /// </summary>
        public string? Version
        {
            get { return version; }
            set { version = value; RaisePropertyChanged(); }
        }


        RepBrand repBrand = null;
        private string? brand;
        /// <summary>
        /// 品牌
        /// </summary>
        public string? Brand
        {
            get { return brand; }
            set { brand = value; RaisePropertyChanged(); }
        }

        RepVehicleSeries repVehicleSeries = null;
        private string? vehicleSeries;
        /// <summary>
        /// 车系
        /// </summary>
        public string? VehicleSeries
        {
            get { return vehicleSeries; }
            set { vehicleSeries = value; RaisePropertyChanged(); }
        }

        RepCarType repCarType = null;
        private string? carType;
        /// <summary>
        /// 车型
        /// </summary>
        public string? CarType
        {
            get { return carType; }
            set { carType = value; RaisePropertyChanged(); }
        }

        ObservableCollection<RepCarPartsCarTypeVersion> repCarPartsList=new ObservableCollection<RepCarPartsCarTypeVersion>();
        public ObservableCollection<RepCarPartsCarTypeVersion> RepCarPartsList
        {
            get { return repCarPartsList; }
            set { repCarPartsList = value; RaisePropertyChanged(); }
        }


        #endregion

        #region 保存事件
        /// <summary>
        /// 提交
        /// </summary>
        /// <param name="vm"></param>
        protected override async void Submit(object? obj)
        {
            // 基础数据判断
            if (string.IsNullOrEmpty(SalesName))
            {
                MsgUtil.Warning("销售名称不可为空"); return;
            }
            List<CarPartsCarTypeVersion> CarPartsCarTypeVersionList = new List<CarPartsCarTypeVersion>();
            var deleteList = repCarPartsList.Where(a => a.Type == 1&&a.State==2);
            foreach (var item in deleteList)
            {
                CarPartsCarTypeVersionList.Add(new CarPartsCarTypeVersion() {
                CarPartsId=item.Id,
                SerialNumber=-1,
                State=2
                });
            }

            var addList = repCarPartsList.Where(a => a.Type == 2&& a.State ==0);
            int i = 0;
            foreach (var item in addList)
            {
                i++;
                CarPartsCarTypeVersionList.Add(new CarPartsCarTypeVersion()
                {
                    CarPartsId = item.Id,
                    SerialNumber = i,
                    State = 0
                });
            }

            // 基础数据判断
            if (string.IsNullOrEmpty(Id))
            {
                // 请求后端接口 
                var res = await HttpHelper<int>.PostAsync(ApiUrl.AddCarTypeVersion, new ReqAddCarTypeVersion()
                {
                    BrandId = repBrand?.Id,
                    VehicleSeriesId=repVehicleSeries?.Id,
                    CarTypeId=repCarType?.Id,
                    Code = Code,
                    Version=Version,
                    SalesName=SalesName,
                    CarPartsCarTypeVersionList=CarPartsCarTypeVersionList,
                }); 

                //  判断结果
                MsgUtil.ShowMsg(res.Code, "新增成功", res.ErrorMsg);
            }
            else
            {
                // 请求后端接口 
                var res = await HttpHelper<int>.PutAsync($"{ApiUrl.UpdateCarTypeVersion}", new ReqUpdateCarTypeVersion()
                {
                    Id = Id,
                    BrandId = repBrand?.Id,
                    VehicleSeriesId = repVehicleSeries?.Id,
                    CarTypeId = repCarType?.Id,
                    Code = Code,
                    Version = Version,
                    SalesName = SalesName,
                    CarPartsCarTypeVersionList = CarPartsCarTypeVersionList,
                });
                // 判断结果
                MsgUtil.ShowMsg(res.Code, "修改成功", res.ErrorMsg);
            }
            this.FromClose();
        }
        #endregion


        protected override async void Query(string? type)
        {
           if (type == "Brand")
            {
                Page_Brand_Query brand_Query = new Page_Brand_Query();
                ((BrandQueryViewModel)brand_Query.DataContext).InformationRequested += Brand_InformationRequested;
                brand_Query.ShowDialog();
            }
            else if (type == "VehicleSeries")
            {
                if(string.IsNullOrWhiteSpace(Brand))
                {
                    MsgUtil.Warning("品牌不可为空");
                    return;
                }

                Page_VehicleSeries_Query brand_VehicleSeries = new Page_VehicleSeries_Query(brandId:repBrand?.Id);
                ((VehicleSeriesQueryViewModel)brand_VehicleSeries.DataContext).InformationRequested += VehicleSeries_InformationRequested;
                brand_VehicleSeries.ShowDialog();
            }
            else if (type == "CarType")
            {
                if (string.IsNullOrWhiteSpace(VehicleSeries))
                {
                    MsgUtil.Warning("车系不可为空");
                    return;
                }              

                Page_CarType_Query brand_CarType = new Page_CarType_Query(vehicleSeries: repVehicleSeries?.Id);
                ((CarTypeQueryViewModel)brand_CarType.DataContext).InformationRequested += CarType_InformationRequested;
                brand_CarType.ShowDialog();
            }

        }

      
        /// <summary>
        /// 品牌
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Brand_InformationRequested(object sender, InformationEventArgs<RepBrand> e)
        {
            // 处理从ChildViewModel传递过来的信息
            repBrand = e.Information;
            Brand = repBrand?.Name;
        }

        /// <summary>
        /// 车系
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void VehicleSeries_InformationRequested(object sender, InformationEventArgs<RepVehicleSeries> e)
        {
            // 处理从ChildViewModel传递过来的信息
            repVehicleSeries = e.Information;
            VehicleSeries= repVehicleSeries?.Name;
        }

        /// <summary>
        /// 车型
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void CarType_InformationRequested(object sender, InformationEventArgs<RepCarType> e)
        {
            // 处理从ChildViewModel传递过来的信息
            repCarType = e.Information;
            CarType = repVehicleSeries?.Name;
            RepCarPartsList = new ObservableCollection<RepCarPartsCarTypeVersion>();
            if (!string.IsNullOrEmpty(repCarType?.Id))
            {
                // 请求后端接口 
                var res = await HttpHelper<List<RepCarParts>>.GetAsync($"{ApiUrl.GetCarPartsByCarTypeId}/{repCarType?.Id}");

                if (res != null && res.Data != null)
                {

                    res.Data.ForEach(carPart => {
                        RepCarPartsList.Add(new RepCarPartsCarTypeVersion()
                        {
                            CarPartsTypeName = carPart.VehicleSeriesCarPartsTypeEntityName,
                            Name=carPart.Name,
                            Code= carPart.Code,
                            State=-1,
                            Type=1
                        });
                    }) ;
                }
                   
            }
        }


        #region 新增
        private bool addBtnEnabled = true;
        public bool AddBtnEnabled
        {
            get { return addBtnEnabled; }
            set { addBtnEnabled = value; RaisePropertyChanged(); }
        }
        /// <summary>
        /// 新增事件
        /// </summary>
        private DelegateCommand? _addCommand;
        /// <summary>
        /// 新增事件
        /// </summary>
        public DelegateCommand AddCommand => _addCommand ?? (_addCommand = new DelegateCommand(Add));
        /// <summary>
        /// 新增
        /// </summary>
        protected  void Add(object? obj) {
            if (string.IsNullOrWhiteSpace(VehicleSeries))
            {
                MsgUtil.Warning("车系不可为空");
                return;
            }
            
            Page_CarParts_Query brand_CarParts = new Page_CarParts_Query(vehicleSeriesId: repVehicleSeries.Id);
            ((CarPartsQueryViewModel)brand_CarParts.DataContext).InformationRequested += CarParts_ListInformationRequested;
            brand_CarParts.ShowDialog();
        }
     
        private void CarParts_ListInformationRequested(object sender, ListInformationEventArgs<RepCarParts> e)
        {
            List<string> carPartsId= RepCarPartsList.Select(a=>a.Id).ToList();
            // 处理从ChildViewModel传递过来的信息
            List<RepCarParts> repCarParts = e.Information.Where(a=>!carPartsId.Contains(a.Id)).ToList();
            // RepCarPartsList.AddRange(repCarParts);
            repCarParts.ForEach(carPart => {
                RepCarPartsList.Add(new RepCarPartsCarTypeVersion()
                {
                    CarPartsTypeName = carPart.VehicleSeriesCarPartsTypeEntityName,
                    Id= carPart.Id,
                    Name = carPart.Name,
                    Code = carPart.Code,
                    State = 0,
                    Type = 2
                });
            });
        }


        #endregion

        #region 批量删除
        private bool batchDeleteBtnEnabled = true;
        public bool BatchDeleteBtnEnabled
        {
            get { return batchDeleteBtnEnabled; }
            set { batchDeleteBtnEnabled = value; RaisePropertyChanged(); }
        }
        /// <summary>
        /// 批量删除事件
        /// </summary>
        private DelegateCommand? _batchDeleteCommand;
        /// <summary>
        /// 批量删除事件
        /// </summary>
        public DelegateCommand BatchDeleteCommand => _batchDeleteCommand ?? (_batchDeleteCommand = new DelegateCommand(BatchDelete));
        protected  void BatchDelete(object? obj) {         
            ObservableCollection<RepCarPartsCarTypeVersion> newCarPartsList = new ObservableCollection<RepCarPartsCarTypeVersion>();
            int n = RepCarPartsList.Count;
            for (int i = 0; i<n; i++)
            {
                RepCarPartsCarTypeVersion carTypeVersion = RepCarPartsList[i];
                if(carTypeVersion.IsSelected&& carTypeVersion.Type == 1)
                {
                    carTypeVersion.State = 2;
                    newCarPartsList.Add(carTypeVersion);
                }
                else
                    newCarPartsList.Add(carTypeVersion);
            }
            RepCarPartsList = newCarPartsList;

        }

        #endregion


        #region 还原
        private bool restoreBtnEnabled = true;
        public bool RestoreBtnEnabled
        {
            get { return restoreBtnEnabled; }
            set { restoreBtnEnabled = value; RaisePropertyChanged(); }
        }
        private DelegateCommand? _restoreCommand;
        public DelegateCommand RestoreCommand => _restoreCommand ?? (_restoreCommand = new DelegateCommand(Restore));
        protected void Restore(object? obj)
        {
            if (obj == null) return;
            var selectCarParts=(RepCarPartsCarTypeVersion)obj;
            ObservableCollection<RepCarPartsCarTypeVersion> newCarPartsList = new ObservableCollection<RepCarPartsCarTypeVersion>();
            int n = RepCarPartsList.Count;
            for (int i = 0; i < n; i++)
            {
                RepCarPartsCarTypeVersion carTypeVersion = RepCarPartsList[i];
                if (carTypeVersion.Id== selectCarParts.Id)
                {
                    carTypeVersion.State = null;
                }
                newCarPartsList.Add(carTypeVersion);

            }
            RepCarPartsList = newCarPartsList;
        }

        #endregion


    }
}
